package com.cxm.support.realm;




import com.cxm.support.entity.User;
import com.cxm.support.service.UserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class AccountRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;



    @Override
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取当前登录用户得信息
        Subject subject= SecurityUtils.getSubject();
        User user= (User) subject.getPrincipal();
        //设置角色
        Set<String> roles=new HashSet<>();
        roles.add(user.getRole());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        info.addStringPermission(user.getPerms());

        return info;
//        return null;
    }





//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        User user=userService.findByUsername(token.getUsername());
        if (user!=null){

            return  new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }





        return null;
    }
}
